package cn.huiyunche.base.service.interfaces.impl;

import cn.huiyunche.base.service.constant.BVehicleConstant;
import cn.huiyunche.base.service.enums.BStowageModelEnum;
import cn.huiyunche.base.service.interfaces.BStowageVehicleService;
import cn.huiyunche.base.service.interfaces.BVehicleClassService;
import cn.huiyunche.base.service.interfaces.SOrderDetailService;
import cn.huiyunche.base.service.mappers.SOrderDetailMapper;
import cn.huiyunche.base.service.model.BStowageModel;
import cn.huiyunche.base.service.model.BVehicleClass;
import cn.huiyunche.base.service.model.SOrderDetail;
import cn.huiyunche.base.service.model.SOrderDetailExample;
import cn.huiyunche.tools.basic.exceptions.BusinessException;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class SOrderDetailServiceImpl implements SOrderDetailService {

    private static final Logger LOGGER = LoggerFactory.getLogger(SOrderDetailServiceImpl.class);

    @Autowired
    private SOrderDetailMapper sOrderDetailMapper;

    @Autowired
    private BVehicleClassService bVehicleClassService;

    @Autowired
    private BStowageVehicleService bStowageVehicleService;

    @Override
    public List<SOrderDetail> getDetailsByOrderId(long orderId) {
        LOGGER.info("getDetailsByOrderId param : {}", orderId);
        if (0 == orderId) {
            LOGGER.error("getDetailsByOrderId orderId must not be 0!");
            throw new IllegalArgumentException("订单id不能是0！");
        }

        SOrderDetailExample example = new SOrderDetailExample();
        example.createCriteria().andOrderIdEqualTo(orderId);
        List<SOrderDetail> list = sOrderDetailMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(list)) {
            LOGGER.error("getDetailsByOrderId list is empty");
            throw new BusinessException("获取订单车辆信息失败！");
        }
        return list;
    }

    @Override
    public SOrderDetail getById(long detailId) {
        LOGGER.info("getById param : {}", detailId);
        if (0 == detailId) {
            LOGGER.error("getById detailId must not be 0!");
            throw new IllegalArgumentException("客户订单详情id不能是0！");
        }
        return sOrderDetailMapper.selectByPrimaryKey(detailId);
    }

    @Override
    public void deleteByCOrderId(long customerOrderId) {
        LOGGER.info("deleteByCOrderId param : {}", customerOrderId);
        if (0 == customerOrderId) {
            LOGGER.error("deleteByCOrderId customerOrderId must not be 0");
            throw new IllegalArgumentException("客户订单id不能是0");
        }

        SOrderDetailExample example = new SOrderDetailExample();
        example.createCriteria().andOrderIdEqualTo(customerOrderId);
        sOrderDetailMapper.deleteByExample(example);
    }

    @Override
    public BigDecimal calculateVehicleClassFactor(BigDecimal baseShippingFee, long customerOrderId) {
        LOGGER.info("calculateVehicleClassFactor params : {}, {}", baseShippingFee, customerOrderId);
        if (null == baseShippingFee) {
            LOGGER.error("calculateVehicleClassFactor baseShippingFee is null");
            throw new IllegalArgumentException("基础运价不能为空");
        }
        if (0 == customerOrderId) {
            LOGGER.error("calculateVehicleClassFactor customerOrderId must not be 0");
            throw new IllegalArgumentException("客户订单id不能是0");
        }

        //获取车辆信息
        List<SOrderDetail> list = this.getDetailsByOrderId(customerOrderId);

        //匹配配置模型
        List<Long> vehicleClassIds = list.stream().map(detail -> detail.getSysVehicleClassid()).collect(Collectors.toList());
        List<Integer> vehicleNum = list.stream().mapToInt(detail -> detail.getAmount()).collect(ArrayList::new, ArrayList::add, ArrayList::addAll);
        BStowageModel model = bStowageVehicleService.computeSuitableStowage(BStowageModelEnum.ORDER, vehicleClassIds, vehicleNum);
        if (null != model) {
            //满足匹配模型-->打折
            baseShippingFee = baseShippingFee.multiply(model.getDiscount());
        }

        //获取车型分类系数
        List<BVehicleClass> classs = bVehicleClassService.getLists(null);
        Map<String, BigDecimal> map = classs.stream().collect(Collectors.toMap(BVehicleClass::getVehicleClass, BVehicleClass::getFactorRatio));

        BigDecimal total = BigDecimal.ZERO.setScale(2);

        for (int i = 0; i < list.size(); i++) {
            SOrderDetail detail = list.get(i);
            BigDecimal factor = map.get(StringUtils.isBlank(detail.getSysVehicleClass()) == true ? BVehicleConstant.DEFAULT_VEHICLE_CLASS : detail.getSysVehicleClass());
            total = total.add(factor.multiply(baseShippingFee).setScale(0, RoundingMode.UP).multiply(BigDecimal.valueOf(detail.getAmount())));
        }

        return total;
    }

}
